package cn.accjiyun.pki.controller.upload;

import cn.accjiyun.pki.common.constants.CommonConstants;
import cn.accjiyun.pki.common.controller.BaseController;
import cn.accjiyun.pki.common.utils.DateUtils;
import cn.accjiyun.pki.common.utils.FileUploadUtils;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;

/**
 * Created by jiyun on 4/18/2017.
 */
@Controller
@RequestMapping("/admin/upload")
public class UploadFileController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(UploadFileController.class);

    /**
     * 获得项目根目录
     */
    private String getProjectRootDirPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    @RequestMapping(value = "/file")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,
                             @RequestParam(value = "file", required = true) MultipartFile file,
                             @RequestParam(value = "param", required = false) String param) {
        try {
            String imageType = "jpg,gif,png,jpeg";
            String documentType = "doc,docx,pdf,rar,zip,cer,pfx";
            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = FileUploadUtils.getSuffix(file.getOriginalFilename());
            if (imageType.contains(ext) && file.getSize() > 4096000L) {
                return responseData("filePath", 400, "上传的图片大小不能超过4M ！", ext, file.getOriginalFilename());
            } else if (documentType.contains(ext) && file.getSize() > 40960000L) {
                return responseData("filePath", 400, "上传的文档大小不能超过40M ！", ext, file.getOriginalFilename());
            } else if (!imageType.contains(ext) && !documentType.contains(ext)) {
                return responseData("filePath", 400, "文件格式错误，上传失败!", ext, file.getOriginalFilename());
            }
            //获取文件路径
            String filePath = getPath(request, ext, param);
            File targetFile = new File(getProjectRootDirPath(request) + filePath);

            //如果目录不存在，则创建
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            //保存文件
            file.transferTo(targetFile);
            logger.info("Upload success to : " + targetFile.getAbsolutePath());
            //返回数据
            return responseData(filePath, 200, "上传成功", ext, file.getOriginalFilename());
        } catch (Exception e) {
            logger.error("uploadFile()--error", e);
            return responseData("filePath", 400, "系统繁忙，上传失败!", null, null);
        }
    }

    /**
     * 返回数据
     *
     * @param url     文件路径
     * @param status  状态 200成功 其状态均为失败
     * @param message 提示信息
     * @return 回调路径
     */
    public String responseData(String url, int status, String message, String ext, String fileTitle) {
        JsonObject resultJson = new JsonObject();
        if (status == 200) {
            resultJson.addProperty("code", 0);
            JsonObject data = new JsonObject();
            data.addProperty("src", url);
            data.addProperty("title", fileTitle);
            resultJson.add("data", data);
        }
        resultJson.addProperty("status", status);
        resultJson.addProperty("msg", message);
        resultJson.addProperty("url", url);
        resultJson.addProperty("ext", ext);
        return gson.toJson(resultJson);
    }


    /**
     * 获取文件保存的路径
     *
     * @param request
     * @param ext 文件后缀
     * @param param 传入参数
     * @return 返回文件路径
     */
    private String getPath(HttpServletRequest request, String ext, String param) {
        String filePath = "/upload/";
        if (param != null && param.trim().length() > 0) {
            filePath += param;
        } else {
            filePath += CommonConstants.projectName;
        }
        filePath += "/" + DateUtils.toString(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + "." + ext;
        return filePath;
    }

}
